const mysql = require('mysql2/promise');

const pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD ,
  database: process.env.DB_NAME ,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 添加测试连接函数
async function testConnection() {
  try {
    const connection = await pool.getConnection();
    console.log('✅ 成功连接到MySQL数据库');
    connection.release();
    
    // 执行简单查询测试
    const [rows] = await pool.query('SELECT 1 + 5 AS result');
    console.log('✅ 简单查询测试通过，结果:', rows[0].result);
  } catch (err) {
    console.error('❌ 连接MySQL数据库失败:', err.message);
    // 提供详细的错误排查建议
    if (err.code === 'ER_ACCESS_DENIED_ERROR') {
      console.log('请检查数据库用户名和密码是否正确');
    } else if (err.code === 'ER_BAD_DB_ERROR') {
      console.log('指定的数据库不存在，请检查数据库名称');
    } else if (err.code === 'ECONNREFUSED') {
      console.log('无法连接到数据库服务器，请检查:');
      console.log('1. MySQL服务是否正在运行');
      console.log('2. 主机地址和端口是否正确');
      console.log('3. 防火墙是否阻止了连接');
    }
    process.exit(1); // 退出应用
  }
}

async function filtrateJobs(filters) {
  let sql = 'SELECT * FROM jobs WHERE 1=1';
  const params = [];

  if(filters.post) {
      sql += 'AND post LIKE ? ';
      params.push(`%${filters.post}%`);
  }

  if (filters.area) {
      sql += ' AND area LIKE ? ';
      params.push(`%${filters.area}%`);
  }

  if (filters.education) {
      sql += ' AND education =?';
      params.push(filters.education)
  }

  const [rows] = await pool.execute(sql,params);
  return rows;
}


// result = filtrateJobs({education:'本科'})
// console.log(result)
// 立即执行测试
// testConnection();

module.exports = pool;